package com.jp.security.service.impl;

import com.jp.security.entity.SecurityUser;
import com.jp.security.entity.User;
import com.jp.security.service.SysLoginService;
import com.jp.security.utils.JwtUtil;
import com.jp.security.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map<String, Object> login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getUsername());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // todo jtw密钥生成
        SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(securityUser.getUsername());
        // todo 把用户权限放入redis
        redisUtil.setCacheObject(securityUser.getUsername(), securityUser);
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }
}
